package com.sinping.qh.service.admin.impl;

import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.user.DocumentDomain;
import com.sinping.qh.domain.user.MessageInfoDomain;
import com.sinping.qh.dto.admin.DocumentDto;
import com.sinping.qh.dto.auth.UserSessionDTO;
import com.sinping.qh.query.base.QueryParams;
import com.sinping.qh.query.document.DocumentQuery;
import com.sinping.qh.repository.mongo.DocumentRepository;
import com.sinping.qh.repository.mongo.MessageInfoRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.IDocumentService;
import com.sinping.qh.service.app.MessageInfo.IMessageInfoService;
import com.sinping.qh.service.app.auth.ISessionMongoService;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class DocumentImpl implements IDocumentService {

    @Autowired
    MongoManager mongoManager;

    @Autowired
    DocumentRepository documentRepository;

    @Autowired
    IMessageInfoService iMessageInfoService;

    @Autowired
    ISessionService iSessionService;

    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;

    @Override
    public ResDto addDocument(HttpServletRequest httpServletRequest, DocumentDto documentDto) {

        String token =httpServletRequest.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null){
            return new ResDto(Const.PARAM_ERROR,"用户未登录");
        }

        if (org.apache.commons.lang.StringUtils.isBlank(userSessionDTO.getId())){
            return new ResDto(Const.SERVER_ERROR,"获取用户信息错误");
        }

        String userId = userSessionDTO.getId();
        String username = userSessionDTO.getUsername();

        try {
            DocumentDomain documentDomain = BeanMapper.map(documentDto, DocumentDomain.class);
            documentDomain.setId(IdGenerator.uuid2());
            documentDomain.setStatus("0");
            documentDomain.setGmtCreated(new Date());//创建时间
            documentDomain.setGmtModified(new Date());//更新时间
            documentDomain.setFileSubmitUserid(userId);
            documentDomain.setFileSubmitUserName(username);
            DocumentDomain saveDomain = documentRepository.save(documentDomain);

            if (saveDomain == null){
                return new ResDto(Const.SERVER_ERROR,"失败");
            }
            else {
                return new ResDto(Const.SUCCESS,"保存成功",documentDomain.getId());
            }
        }
        catch (Exception e){
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR,"添加异常");
        }
    }

    @Override
    public ResDto deleteDocumentById(String id) {

        if (StringUtils.isBlank(id)){
            return new ResDto(Const.PARAM_ERROR,"id不能为空");
        }
        try {
            DocumentDomain documentDomain = documentRepository.findOne(id);
            if (documentDomain == null){
                return new ResDto(Const.SERVER_ERROR,"没有该记录");
            }
            documentDomain.setStatus(CommonDbConst.DB_DELETE_LOGICAL);
            DocumentDomain save = documentRepository.save(documentDomain);
            if (save == null){
                return new ResDto(Const.SERVER_ERROR,"删除失败");
            }
            else {

                iMessageInfoService.deleteMessageInfoByDocId(id);

                return new ResDto(Const.SUCCESS,"删除成功");
            }

        }
        catch (Exception e){
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR,"删除异常");
        }
    }

    @Override
    public ResDto getDocumentById(String id) {

        if (StringUtils.isBlank(id)){
            return new ResDto(Const.PARAM_ERROR,"id不能为空");
        }
        try {
            DocumentDomain documentDomain = documentRepository.findOne(id);
            if (documentDomain == null){
                return new ResDto(Const.SERVER_ERROR,"没有该记录");
            }

            ResDto resDto = new ResDto();
            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("成功");
            DocumentDto documentDto = BeanMapper.map(documentDomain, DocumentDto.class);

            if (org.apache.commons.lang.StringUtils.isNotBlank(documentDto.getFilePath())){
                documentDto.setFilePath(urlPath+documentDto.getFilePath());
            }

            resDto.setDatas(JsonMapper.defaultMapper().toJson(documentDto));
            return resDto;

        }
        catch (Exception e){
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR,"查询详情异常");
        }
    }

    @Override
    public ResDto getDocumentListFrontPage(FrontPage frontPage) {

        DocumentQuery documentQuery = new DocumentQuery();
        Map<String,String> condition = frontPage.getCondition();
        if (condition == null || condition.isEmpty()){
        }
        else {
            String conditionStr = JsonMapper.defaultMapper().toJson(condition);
            DocumentDto documentDto = JsonMapper.defaultMapper().fromJson(conditionStr, DocumentDto.class);
            documentQuery.setFileName(documentDto.getFileName());
            documentQuery.setFileType(documentDto.getFileType());
        }

        documentQuery.setStatus(CommonDbConst.DB_DELETE_NORMAL);

        try {
            Pageable pageable = new PageRequest(frontPage.getPage()-1,frontPage.getSize(), new Sort(Sort.Direction.DESC,"gmt_created"));
            Page<DocumentDomain> page = mongoManager.findPage(documentQuery, pageable,DocumentDomain.class);

            List<DocumentDomain> list = page.getContent();
            for (DocumentDomain model:list) {
                if (org.apache.commons.lang.StringUtils.isNotBlank(model.getFilePath())){
                    model.setFilePath(urlPath+model.getFilePath());
                }
            }

            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setMsg("成功");
            ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto,page,DocumentDto.class,frontPage);
            return resDto;
        }
        catch (Exception e){
            e.printStackTrace();;
            return new ResDto(Const.SERVER_ERROR,"分页查询异常");
        }

    }
}
